import Vue from 'vue';
import {Modal} from 'ant-design-vue';
import {camelize} from 'ant-design-vue/lib/_util/props-util.js';

export function isEmpty(obj) {
  if (!obj || obj === '' || (Array.isArray(obj) && obj.length === 0)) return true;
  if (typeof obj === 'object' && Object.keys(obj).length === 0) return true;
  return false;
}

export function guid() {
  const timestamp = new Date().getTime(); // 获取当前时间戳
  const randomNum1 = Math.floor(Math.random() * 1000); // 生成一个0-999之间的随机数
  const randomNum2 = Math.floor(Math.random() * 1000); // 生成一个0-999之间的随机数
  return `${timestamp}${randomNum1}${randomNum2}`; // 返回拼接后的ID字符串
}

export function openModal(component, props = {}, ok, close) {
  Vue.use(Modal);
  let div = createElement();

  let app = new Vue({
    render(h) {
      return h(component, {
        ref: 'modal', props, on: {
          close: () => {
            setTimeout(() => app.$destroy(), 300);
            close && close(...args);
          },
          ok: (...args) => {
            ok && ok(...args);
          },
        }
      });
    }, methods: {
      open() {
        this.$refs.modal.open();
      }
    }
  });
  app.$mount(div);
  app.open();
  return app;
}

export function createElement(tagName = 'div') {
  let el = document.createElement('div');
  document.body.append(el);
  return el;
}

export function isVnodeFormComponent(vnode, componentName) {
  return vnode.componentOptions
    && vnode.componentOptions.tag
    && camelize(vnode.componentOptions.tag).toLowerCase() === camelize(componentName).toLowerCase();
}

export function createModelProps() {
  return {
    props: 'value',
    event: 'change'
  }
}

export function createPagination() {
  return {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30', '50', '100'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '条'
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  }
}

export function createProps(type, defaultValue) {
  if(type === Boolean) return {type: Boolean, default: defaultValue || false};
  if(type === String) return {type: String, default: defaultValue || undefined};
  if(type === Object) return {type: Object, default: defaultValue || (() => ({}))};
  if(type === Array) return {type: Array, default: defaultValue || (() => [])};
  if(type === Function) return {type: Function, default: defaultValue || undefined};
  if(type === Number) return {type: Number, default: defaultValue || undefined};
}

export function clearSelection () {
  if (window.getSelection) {
    window.getSelection().removeAllRanges();
  } else if (document.selection) {
    document.selection.empty();
  }
}